package com.chagee.store.operation.server.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chagee.lark.anno.ExceptionLarkNotice;
import com.chagee.lark.enums.UrgentTypeEnum;
import com.chagee.store.operation.api.enums.*;
import com.chagee.store.operation.server.entity.*;
import com.chagee.store.operation.server.event.service.*;
import com.chagee.store.operation.server.service.biz.TaskExecutionBizService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author : hk
 * @Date : 2024/11/26
 */

@Slf4j
@Service
public class WorkOrderAcceptanceService {

	@Resource
	private WorkOrderBaseService workOrderBaseService;
	@Resource
	private TaskExecutionBaseService taskExecutionBaseService;
	@Resource
	private TaskExecutionBizService taskExecutionBizService;
	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;


	@ExceptionLarkNotice(bizType = "自动验收工单", title = "自动验收打烊工单和打烊任务", urgentType = UrgentTypeEnum.APP_PHONE)
	public void acceptance(List<String> storeCodeList){
		QueryWrapper<WorkOrderDO> allWrapper = Wrappers.query();
		allWrapper.eq("document_status", StoreWorkOrderStatusEnum.TO_BE_ACCEPTED.getType());
		allWrapper.in("store_code", storeCodeList);

		List<WorkOrderDO> workOrderDOS = workOrderBaseService.list(allWrapper);

		//待验收单据 更新单据下任务
		if (CollectionUtils.isNotEmpty(workOrderDOS)) {
			//待验收状态单据下任务为合格(系统)
			List<String> workOrderNumbers = workOrderDOS.stream().map(WorkOrderDO::getWorkOrderNumber).collect(Collectors.toList());
			QueryWrapper<TaskExecutionDO> query = Wrappers.query();
			query.in("work_order_number", workOrderNumbers);
			List<TaskExecutionDO> taskExecutionDOList = taskExecutionBaseService.list(query);
			List<TaskExecutionDO> result = taskExecutionDOList.stream().peek(s -> {
				if (StringUtils.isEmpty(s.getEarlyAcceptance())) {
					//单据下任务状态默认合格(系统)
					s.setEarlyAcceptance(StoreTaskEnum.SYSTEM_SATISFIED.getType());
					s.setReliableTime(new Date());
				}
			}).collect(Collectors.toList());
			taskExecutionBizService.updateBatch(result);

			Map<String, List<TaskExecutionDO>> taskMap = result.stream().collect(Collectors.groupingBy(TaskExecutionDO::getWorkOrderNumber));

			workOrderDOS.forEach(s -> {
				//单据状态已验收变更为已完成
				s.setDocumentStatus(StoreWorkOrderStatusEnum.COMPLETED.getType());
				s.setAcceptanceCompletionTime(new Date());
				List<TaskExecutionDO> orderTaskList = taskMap.get(s.getWorkOrderNumber());
				//List<TaskExecutionDO> orderTaskList = result.stream().filter(taskDO -> StringUtils.equals(s.getWorkOrderNumber(), taskDO.getWorkOrderNumber())).collect(Collectors.toList());
				//计算合格率
				List<TaskExecutionDO> yesOrders = orderTaskList.stream().filter(executionDO -> StringUtils.equals(StoreTaskEnum.YES.getType(), executionDO.getEarlyAcceptance()) || StringUtils.equals(StoreTaskEnum.SYSTEM_SATISFIED.getType(), executionDO.getEarlyAcceptance())).collect(Collectors.toList());
				List<TaskExecutionDO> emptyOrders = orderTaskList.stream().filter(executionDO -> StringUtils.equals(StoreTaskEnum.EMPTY.getType(), executionDO.getEarlyAcceptance())).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(yesOrders)) {
					// 工单评分  满意数量 / (总数量- 验收无此项) * 100
					BigDecimal score = new BigDecimal(yesOrders.size() * 100).divide(new BigDecimal(orderTaskList.size() - emptyOrders.size()), 0, BigDecimal.ROUND_HALF_UP);
					s.setDocumentScore(score.toString());
				} else {
					s.setDocumentScore("0");
				}
				boolean anyMatch = orderTaskList.stream().anyMatch(t -> StoreTaskEnum.TASK_ACCEPTANCE_TYPE.contains(t.getEarlyAcceptance()));
				if (anyMatch) {
					s.setAcceptanceType(OrderAcceptanceTypeEnum.HAND.name());
				} else {
					s.setAcceptanceType(OrderAcceptanceTypeEnum.SYSTEM.name());
				}
			});
			log.info("门店下待验收状态工单：" + JSONObject.toJSON(workOrderNumbers) + "自动验收! 变更工单状态和该工单任务状态");
			workOrderBaseService.updateBatchById(workOrderDOS);

			Map<String, WorkOrderDO> workOrderDOMap = workOrderDOS.stream().collect(Collectors.toMap(WorkOrderDO::getWorkOrderNumber, Function.identity(), (a, b) -> a));
			LambdaQueryWrapper<WorkOrderReceiverDO> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.in(WorkOrderReceiverDO::getWorkOrderNumber, workOrderNumbers);
			List<WorkOrderReceiverDO> workOrderReceiverDOS = workOrderReceiverBaseService.list(queryWrapper);
			workOrderReceiverDOS.forEach(s -> {
				s.setDocumentStatus(StoreWorkOrderStatusEnum.COMPLETED.getType());
				if (Objects.nonNull(workOrderDOMap.get(s.getWorkOrderNumber()))) {
					s.setDocumentScore(workOrderDOMap.get(s.getWorkOrderNumber()).getDocumentScore());
				}
			});
			workOrderReceiverBaseService.updateBatchById(workOrderReceiverDOS);
		}
	}
}
